<?php

namespace App\Kuafu\Base\Controller;

use App\Exceptions\BaseException;
use App\Http\Controllers\Controller;
use App\Kuafu\Base\Enum\BaseCodeEnum;
use App\Kuafu\Base\Service\BaseService;
use Illuminate\Http\Request;

class BaseController extends Controller
{
    /**
     * @var string 程序版本
     */
    public $version = '0.0.1';

    public int    $brandId = 0;
    public int    $shopId  = 0;

    public function __construct(Request $request)
    {
        $this->brandId = (int)$request->header('brandId');
        $this->shopId  = (int)$request->header('shopId');
    }

    /**
     * Json 返回
     *
     * @param array $data
     * @return \Illuminate\Http\JsonResponse
     */
    public function json(array $data = [])
    {
        return response()->json($data)->header('Content-Type', 'application/json;charset=utf-8');
    }

    public function success(array $data = null)
    {
        return $this->json(['code' => BaseCodeEnum::OK, 'msg' => '', 'data' => $data ?: null]);
    }

    public function fail(int $code, string $msg = '', array $data = null)
    {
        // 默认的模块
        BaseException::setModule(BaseService::getModuleByNameSpace(static::class));

        if (empty($msg)) {
            $msg = BaseCodeEnum::getCodeTextAutoClass($code);
        }

        return $this->json(['code' => $code, 'msg' => $msg, 'data' => $data ?: null]);
    }
}
